//
//  ChooseViewController.m
//  JSReader
//
//  Created by xzoscar on 16/6/19.
//  Copyright © 2016年 hujs. All rights reserved.
//

#import "ChooseViewController.h"
#import "JSFileHandler.h"
#import "ClickableUIImageView.h"
#import "MiddleViewController.h"
#import "MiddleViewController.h"
#import "LeftViewController.h"
#import "RightViewController.h"
#import "BaseNavController.h"
#import "MMDrawerController.h"
#define kViewHeight  120 * kScreenHeight/568

@interface ChooseViewController ()

@property (strong, nonatomic) MMDrawerController *drawer;

@end

@implementation ChooseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title  = @"金庸全集";
    if([[JSFileHandler shared] updateBookList]) {
        [self setupView];
    } else {
        DLog(@"读取错误");
    }
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSString *bookName = [[NSUserDefaults standardUserDefaults] objectForKey:kBookName];
    if (bookName.length) {
        Book *book = [[JSFileHandler shared] readLastReadBook:bookName];
        [self showMianVCWithBook:book];
    }
    
}

- (void)setupView {
    UIScrollView *scroll = [[UIScrollView alloc ]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    
    
    [self.view addSubview:scroll];
    
    NSArray *books =  [[JSFileHandler shared] allBooks];
    for (int i = 0; i < books.count; i++) {
        UIView *view = [self viewWithIndex:i];
        
        CGRect frame = CGRectMake(0, 0,ceil(view.frame.size.width * 0.8) ,ceil(view.frame.size.height * 0.9) );
        
        ClickableUIImageView *iView =[self clickableImageViewWithFrame:frame imageName:books[i]]; ;
        iView.center = CGPointMake(view.frame.size.width/2, view.frame.size.height/2);
        
        [view addSubview:iView];
        
        [scroll addSubview:view];
        if (i == books.count -1) {
            //到最后一本书，设置一下scrollview
            scroll.contentSize = CGSizeMake(kScreenWidth, view.frame.origin.y+kViewHeight);
        }
    }
   
    
}

- (UIView *)viewWithIndex:(int)i {
    CGRect frame = CGRectMake(i%3*kScreenWidth/3, i/3*kViewHeight, kScreenWidth/3, kViewHeight);
    UIView *view = [[UIView alloc ] initWithFrame:frame];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}

- (ClickableUIImageView *)clickableImageViewWithFrame:(CGRect)frame imageName:(NSString *)name {
    __weak typeof(self) weakSelf = self;
    ClickableUIImageView *iView = [[ClickableUIImageView alloc] initWithFrame:frame imageName:[NSString stringWithFormat:@"%@.jpg", name] handleClick:^(NSString *bookName) {
        DLog(@"%@ clicked!", bookName);
        [weakSelf showMianVC:bookName];
    }];
    return iView;
}

- (void)showMianVCWithBook:(Book *)book {
    if (!book) {
        DLog(@"book 为空");
        return;
    }
    [[JSFileHandler shared] setSelectedBookName:book.name];
    
    __weak typeof(self) weakSelf = self;
    [[JSFileHandler shared] loadBookWithName:[[JSFileHandler shared] selectedBookName] lastReadBook:book completionHandler:^(Book *selectedBook) {
        [weakSelf loadUIWithBook:[[JSFileHandler shared] selectedBook]];
        
    }];

}

- (void)showMianVC:(NSString *)bookName {
    if (bookName.length == 0) {
        return;
    }
    
    if (![[[JSFileHandler shared] allBooks] containsObject:bookName] ) {
        DLog(@"不知此书在何处!");
        return;
    }
    [[JSFileHandler shared] setSelectedBookName:bookName];
    
    __weak typeof(self) weakSelf = self;
    [[JSFileHandler shared] loadBookWithName:[[JSFileHandler shared] selectedBookName] lastReadBook:nil completionHandler:^(Book *selectedBook) {
        [weakSelf loadUIWithBook:[[JSFileHandler shared] selectedBook]];
        
    }];
   
    
}

- (void)loadUIWithBook:(Book *)book {
    if (!book) {
        DLog(@"book 不能为空");
        return;
    }
    
    NSString *htmlName = book.chapterAndHTMLDict[book.selectedChapter];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",kOneBookPath([[JSFileHandler shared] selectedBookName]), htmlName ] ;
    NSURL *url = [NSURL fileURLWithPath:filePath];
    
    
    if (self.drawer == nil) {
        MiddleViewController *VC = [[MiddleViewController alloc] initWithURL:url];
        
        BaseNavController *nav = [[BaseNavController alloc] initWithRootViewController:VC];
        
        LeftViewController *leftvc = [[LeftViewController alloc] initWithNibName:@"LeftViewController" bundle:nil];
        BaseNavController *navLeft = [[BaseNavController alloc] initWithRootViewController:leftvc];
        
        RightViewController *rightvc = [[RightViewController alloc] initWithNibName:@"RightViewController" bundle:nil];
        BaseNavController *navRight = [[BaseNavController alloc] initWithRootViewController:rightvc];
        
        MMDrawerController *drawer = [[MMDrawerController alloc] initWithCenterViewController:nav leftDrawerViewController:navLeft rightDrawerViewController:navRight];
        
        [drawer setShowsShadow:YES];
        
        [drawer setMaximumRightDrawerWidth:kScreenWidth * 0.4];
        [drawer setMaximumLeftDrawerWidth:kScreenWidth * 0.7];
        
        [drawer setOpenDrawerGestureModeMask:
         MMOpenDrawerGestureModeCustom|
         MMOpenDrawerGestureModeBezelPanningCenterView|MMOpenDrawerGestureModePanningNavigationBar
         
         ];
        
        [drawer setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeCustom|MMCloseDrawerGestureModePanningDrawerView|
         MMCloseDrawerGestureModeTapNavigationBar|
         MMCloseDrawerGestureModeBezelPanningCenterView|
         MMCloseDrawerGestureModePanningNavigationBar|
         MMCloseDrawerGestureModePanningCenterView];
        
        
        [drawer setGestureShouldRecognizeTouchBlock:^BOOL(MMDrawerController *drawerController, UIGestureRecognizer *gesture, UITouch *touch) {
            BOOL shouldRecognizeTouch = NO;
            if (drawerController.openSide == MMDrawerSideNone && [gesture isKindOfClass:[UIGestureRecognizer class]] ) {
                UINavigationController *nav = (UINavigationController *)[drawerController centerViewController];
                UIWebView *view = [(MiddleViewController *)[nav.viewControllers firstObject] webView];
                CGPoint location = [touch locationInView:view];
                shouldRecognizeTouch = CGRectContainsPoint(CGRectMake(20, view.frame.origin.y, view.frame.size.width - 40, view.frame.size.height), location);
            }
            return shouldRecognizeTouch;
        }];
        self.drawer = drawer;
    }
        else {
//        [[NSNotificationCenter defaultCenter]
//                 postNotificationName:kLoadChapterNotify
//                 object:nil
//                 userInfo:@{
//                            kChapterName : book.selectedChapter,
//                                    kBook: book
//                                                }];
    }
    
   
    
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    
    window.rootViewController = self.drawer ;
   
    [UIView transitionWithView:window
                      duration:0.3
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:nil
                    completion:nil];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
